<script setup lang="ts">
const route = useRoute()
const toast = useToast()
const { loggedIn } = useUserSession()

// 如果已经登录，重定向到首页
if (loggedIn.value) {
  await navigateTo('/')
}

const email = ref('')
const password = ref('')
const confirmPassword = ref('')
const nickname = ref('')
const verificationCode = ref('')
const loading = ref(false)
const error = ref('')
const codeSent = ref(false)
const countdown = ref(0)

// 倒计时
const startCountdown = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 发送验证码
async function sendCode() {
  if (!email.value) {
    error.value = '请输入邮箱地址'
    return
  }

  // 验证邮箱格式
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(email.value)) {
    error.value = '邮箱格式不正确'
    return
  }

  try {
    const response = await $fetch('/api/send-verification-code', {
      method: 'POST',
      body: { email: email.value },
    })

    if (response.statusCode === 200) {
      toast.add({
        title: '验证码已发送',
        description: '请查收您的邮箱',
        icon: 'i-lucide-check-circle',
        color: 'success',
      })
      codeSent.value = true
      startCountdown()
    } else {
      error.value = response.statusMessage || '发送验证码失败'
    }
  } catch (err: any) {
    error.value = err.data?.statusMessage || '发送验证码失败，请检查网络连接'
  }
}

// 验证密码强度
function validatePassword(password: string): string | null {
  if (password.length < 6) {
    return '密码长度至少6位'
  }
  if (!/[A-Z]/.test(password)) {
    return '密码必须包含至少一个大写字母'
  }
  if (!/[a-z]/.test(password)) {
    return '密码必须包含至少一个小写字母'
  }
  if (!/\d/.test(password)) {
    return '密码必须包含至少一个数字'
  }
  return null
}

async function handleRegister() {
  // 表单验证
  if (
    !email.value ||
    !password.value ||
    !confirmPassword.value ||
    !nickname.value ||
    !verificationCode.value
  ) {
    error.value = '请填写所有必填项'
    return
  }

  // 验证邮箱格式
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(email.value)) {
    error.value = '邮箱格式不正确'
    return
  }

  const passwordError = validatePassword(password.value)
  if (passwordError) {
    error.value = passwordError
    return
  }

  if (password.value !== confirmPassword.value) {
    error.value = '两次输入的密码不一致'
    return
  }

  loading.value = true
  error.value = ''

  try {
    const response = await $fetch('/api/register', {
      method: 'POST',
      body: {
        email: email.value,
        password: password.value,
        nickname: nickname.value,
        verificationCode: verificationCode.value,
      },
    })

    if (response.statusCode === 200) {
      toast.add({
        title: '注册成功',
        description: response.statusMessage,
        icon: 'i-lucide-check-circle',
        color: 'success',
      })

      // 注册成功后跳转到登录页面
      await navigateTo('/login')
    } else {
      error.value = response.statusMessage || '注册失败'
    }
  } catch (err: any) {
    error.value = err.data?.statusMessage || '注册失败，请检查网络连接'
  } finally {
    loading.value = false
  }
}

function goToLogin() {
  navigateTo('/login')
}

function goToHome() {
  navigateTo('/')
}

// 设置页面元数据
useHead({
  title: '用户注册',
  meta: [{ name: 'description', content: '用户注册页面' }],
})
</script>

<template>
  <div
    class="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900"
  >
    <div class="max-w-md w-full space-y-8">
      <!-- 头部 -->
      <div class="text-center">
        <NuxtLink
          to="/"
          class="inline-flex items-center gap-2 text-primary hover:text-primary-600 transition-colors"
        >
          <UIcon name="i-lucide-arrow-left" class="w-5 h-5" />
          <span>返回首页</span>
        </NuxtLink>
        <h2 class="mt-6 text-3xl font-extrabold text-gray-900 dark:text-white">
          用户注册
        </h2>
        <p class="mt-2 text-sm text-gray-600 dark:text-gray-400">
          请填写以下信息完成注册
        </p>
      </div>

      <!-- 注册表单 -->
      <div
        class="bg-white dark:bg-gray-800 py-8 px-4 shadow sm:rounded-lg sm:px-10"
      >
        <form class="space-y-6" @submit.prevent="handleRegister">
          <!-- 邮箱输入 -->
          <div>
            <label
              for="email"
              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
            >
              邮箱地址
            </label>
            <div class="mt-1">
              <input
                id="email"
                v-model="email"
                type="email"
                required
                class="appearance-none relative block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 placeholder-gray-500 dark:placeholder-gray-400 text-gray-900 dark:text-white bg-white dark:bg-gray-700 rounded-md focus:outline-none focus:ring-primary focus:border-primary focus:z-10 sm:text-sm"
                placeholder="请输入邮箱地址"
                :disabled="loading"
              />
            </div>
          </div>

          <!-- 昵称输入 -->
          <div>
            <label
              for="nickname"
              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
            >
              昵称
            </label>
            <div class="mt-1">
              <input
                id="nickname"
                v-model="nickname"
                type="text"
                required
                class="appearance-none relative block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 placeholder-gray-500 dark:placeholder-gray-400 text-gray-900 dark:text-white bg-white dark:bg-gray-700 rounded-md focus:outline-none focus:ring-primary focus:border-primary focus:z-10 sm:text-sm"
                placeholder="请输入昵称"
                :disabled="loading"
              />
            </div>
          </div>

          <!-- 密码输入 -->
          <div>
            <label
              for="password"
              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
            >
              密码
            </label>
            <div class="mt-1">
              <input
                id="password"
                v-model="password"
                type="password"
                required
                class="appearance-none relative block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 placeholder-gray-500 dark:placeholder-gray-400 text-gray-900 dark:text-white bg-white dark:bg-gray-700 rounded-md focus:outline-none focus:ring-primary focus:border-primary focus:z-10 sm:text-sm"
                placeholder="请输入密码（至少6位，包含大小写字母和数字）"
                :disabled="loading"
              />
            </div>
            <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
              密码至少6位，必须包含大小写字母和数字
            </p>
          </div>

          <!-- 确认密码 -->
          <div>
            <label
              for="confirmPassword"
              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
            >
              确认密码
            </label>
            <div class="mt-1">
              <input
                id="confirmPassword"
                v-model="confirmPassword"
                type="password"
                required
                class="appearance-none relative block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 placeholder-gray-500 dark:placeholder-gray-400 text-gray-900 dark:text-white bg-white dark:bg-gray-700 rounded-md focus:outline-none focus:ring-primary focus:border-primary focus:z-10 sm:text-sm"
                placeholder="请再次输入密码"
                :disabled="loading"
              />
            </div>
          </div>

          <!-- 验证码 -->
          <div>
            <label
              for="verificationCode"
              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
            >
              验证码
            </label>
            <div class="mt-1 flex gap-2">
              <input
                id="verificationCode"
                v-model="verificationCode"
                type="text"
                required
                class="flex-1 appearance-none relative block px-3 py-2 border border-gray-300 dark:border-gray-600 placeholder-gray-500 dark:placeholder-gray-400 text-gray-900 dark:text-white bg-white dark:bg-gray-700 rounded-md focus:outline-none focus:ring-primary focus:border-primary focus:z-10 sm:text-sm"
                placeholder="请输入验证码"
                :disabled="loading"
              />
              <button
                type="button"
                :disabled="loading || countdown > 0"
                class="px-4 py-2 text-sm font-medium text-white bg-primary rounded-md hover:bg-primary-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                @click="sendCode"
              >
                {{ countdown > 0 ? `${countdown}s` : '发送验证码' }}
              </button>
            </div>
          </div>

          <!-- 错误提示 -->
          <div v-if="error" class="rounded-md bg-red-50 dark:bg-red-900/20 p-4">
            <div class="flex">
              <UIcon
                name="i-lucide-alert-circle"
                class="flex-shrink-0 h-5 w-5 text-red-400"
              />
              <div class="ml-3">
                <h3 class="text-sm font-medium text-red-800 dark:text-red-200">
                  {{ error }}
                </h3>
              </div>
            </div>
          </div>

          <!-- 注册按钮 -->
          <div>
            <button
              type="submit"
              :disabled="loading"
              class="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-primary hover:bg-primary-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              <UIcon
                v-if="loading"
                name="i-lucide-loader-2"
                class="animate-spin -ml-1 mr-2 h-4 w-4"
              />
              {{ loading ? '注册中...' : '注册' }}
            </button>
          </div>

          <!-- 登录链接 -->
          <div class="text-center">
            <span class="text-sm text-gray-600 dark:text-gray-400"
              >已有账号？</span
            >
            <button
              type="button"
              class="text-sm text-primary hover:text-primary-600 underline ml-1 transition-colors"
              @click="goToLogin"
            >
              立即登录
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>
